package net.begincode.maiev.monitor.http;

import net.begincode.maiev.bean.MonitorBean;
import net.begincode.maiev.bean.SummaryBean;
import net.begincode.maiev.handler.SummaryTaskHandler;
import net.begincode.maiev.model.MonitorSummary;
import net.begincode.maiev.monitor.data.DataOperation;
import net.begincode.maiev.util.ListUtils;
import net.begincode.maiev.util.SpringApplicationContextHolder;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Stay on 2017/6/14  11:41.
 */
@Component
public class HttpDataOperation implements DataOperation {

    @Override
    public void handle(Object data) {
        List list = (List)data;
        SummaryBean summaryBean = null;
        if(!CollectionUtils.isEmpty(list)) {
            int length = list.size();
            summaryBean = new SummaryBean();
            summaryBean.setProjectId(Integer.valueOf(list.get(length - 1).toString()));
            list.remove(length - 1);
            summaryBean.setListBean(list);
            saveData(summaryBean);//把数据写入数据库
        }
    }
    /**
     * 批量插入数据
     *
     * @param summaryList
     * @return
     */
    public void saveBatchList(List<MonitorSummary> summaryList) {
        SummaryTaskHandler summaryTaskHandler = (SummaryTaskHandler) SpringApplicationContextHolder.getSpringBean("summaryTaskHandler");
        summaryTaskHandler.saveBatchList(summaryList);
    }

    public void saveData(SummaryBean summaryBean) {
        List<MonitorSummary> summaryList = handleData(summaryBean);
        if (summaryList != null) {
            saveBatchList(summaryList);
        }
    }

    private List<MonitorSummary> handleData(SummaryBean summaryBean) {
        MonitorSummary monitorSummary = null;
        MonitorBean monitorBean = null;
        int projectId = summaryBean.getProjectId();
        List<MonitorBean> list = summaryBean.getListBean();
        if (!ListUtils.isNull(list)) {
            List<MonitorSummary> summaryList = new ArrayList<>(list.size());
            for (int i = 0; i < list.size(); i++) {
                monitorBean = list.get(i);
                monitorSummary = new MonitorSummary();
                monitorSummary.setMonitorName(monitorBean.getMonitorName());
                monitorSummary.setCreateDate(monitorBean.getDate());
                monitorSummary.setMaxRequestTime(monitorBean.getMaxRequestTime().get());
                monitorSummary.setMonitorHost(monitorBean.getHost());
                monitorSummary.setRequestCount(monitorBean.getRequestCount().get());
                monitorSummary.setRequestType(monitorBean.getRequestType());
                monitorSummary.setTotalRequestTime(monitorBean.getTotalRequestTime().get());
                monitorSummary.setProjectId(projectId);
                summaryList.add(monitorSummary);
            }
            return summaryList;
        }
        return null;
    }
}
